
//按键消抖模块
module key_debountce(
	input 			sys_clk,
	input 			sys_rst_n,
	
	input 			key,
	output	reg		key_val,
	output	reg		key_flag
);

reg			key_reg;
reg [19:0]	delay_cnt;

//消抖
always @(posedge sys_clk or negedge sys_rst_n)	begin
	if(!sys_rst_n)	begin
		key_reg <= 1'b1;
		delay_cnt <= 20'd0;
	end
	else	begin
		key_reg <= key;	//key是外部输入的键值，非阻塞赋值
		if(key != key_reg)
			delay_cnt <= 20'd100_0000;
		else	begin
			if(delay_cnt > 0)
				delay_cnt <= delay_cnt - 1'b1;
			else
				delay_cnt <= 20'd0;
		end
	end
end

always @(posedge sys_clk or negedge sys_rst_n)	begin
	if(!sys_rst_n)	begin
		key_val  <= 1'b1;
		key_flag <= 1'b0;
	end
	else	begin
		if(delay_cnt == 20'd1)	begin
			key_val  <= key;
			key_flag <= 1'b1;
		end
		else	begin
			key_val  <= key_val;
			key_flag <= 1'b0;
		end
	end
end

endmodule